<template>
  <a-modal
    :open="modalVisible"
    @update:open="handleModalVisibleChange"
    title="数据库表结构"
    width="1000px"
    :footer="null"
  >
    <div class="table-structure-container">
      <!-- 数据源信息 -->
      <div class="datasource-info" v-if="dataSource">
        <a-descriptions :column="2" size="small" bordered>
          <a-descriptions-item label="数据源名称">
            {{ dataSource.name }}
          </a-descriptions-item>
          <a-descriptions-item label="数据库类型">
            <a-tag :color="dataSource.db_type === 'mysql' ? 'blue' : 'green'">
              {{ dataSource.db_type.toUpperCase() }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="主机地址">
            {{ dataSource.host }}:{{ dataSource.port }}
          </a-descriptions-item>
          <a-descriptions-item label="数据库名">
            {{ dataSource.database_name }}
          </a-descriptions-item>
        </a-descriptions>
      </div>

      <!-- 表选择 -->
      <div class="table-selection">
        <a-space>
          <a-select
            v-model:value="selectedTable"
            placeholder="请选择要查看的表"
            style="width: 300px"
            show-search
            :filter-option="filterTableOption"
            :loading="loading"
            @change="handleTableChange"
          >
            <a-select-option
              v-for="table in availableTables"
              :key="table"
              :value="table"
            >
              {{ table }}
            </a-select-option>
          </a-select>
          <a-button
            type="primary"
            :loading="loading"
            @click="loadAvailableTables"
          >
            <template #icon><ReloadOutlined /></template>
            刷新表列表
          </a-button>
        </a-space>
      </div>

      <!-- 表结构信息 -->
      <div class="table-structure" v-if="selectedTable && tableStructure">
        <a-divider>
          <span>
            表结构：{{ selectedTable }}
            <a-button
              type="link"
              size="small"
              @click="handleCreateSyncTask"
            >
              <template #icon><PlusOutlined /></template>
              创建同步任务
            </a-button>
          </span>
        </a-divider>

        <!-- 表格列信息 -->
        <a-table
          :columns="columnColumns"
          :data-source="tableStructure.columns"
          :loading="loading"
          row-key="name"
          size="small"
          :pagination="false"
          :scroll="{ x: 1200 }"
          class="structure-table"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'name'">
              <a-space>
                <KeyOutlined v-if="record.primary_key" style="color: #1890ff" />
                {{ record.name }}
              </a-space>
            </template>
            <template v-if="column.key === 'type'">
              <a-tag color="blue">{{ record.type }}</a-tag>
            </template>
            <template v-if="column.key === 'nullable'">
              {{ record.nullable ? '是' : '否' }}
            </template>
            <template v-if="column.key === 'primary_key'">
              <a-tag v-if="record.primary_key" color="gold">主键</a-tag>
              <span v-else>-</span>
            </template>
            <template v-if="column.key === 'default'">
              <code v-if="record.default">{{ record.default }}</code>
              <span v-else>-</span>
            </template>
            <template v-if="column.key === 'comment'">
              <span v-if="record.comment" :title="record.comment">{{ record.comment }}</span>
              <span v-else style="color: #999;">-</span>
            </template>
            <template v-if="column.key === 'suggested_mapping'">
              <a-select
                v-model:value="record.suggested_mapping"
                placeholder="建议映射到..."
                style="width: 200px"
                allow-clear
                @change="handleMappingChange(record, $event)"
              >
                <a-select-option
                  v-for="field in targetFields"
                  :key="field.value"
                  :value="field.value"
                >
                  {{ field.label }}
                </a-select-option>
              </a-select>
            </template>
          </template>
        </a-table>

        <!-- 字段映射预览 -->
        <div v-if="mappedFields.length > 0" class="mapping-preview">
          <a-divider>字段映射预览</a-divider>
          <a-table
            :columns="mappingColumns"
            :data-source="mappedFields"
            size="small"
            :pagination="false"
            class="mapping-table"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'target_field'">
                <a-tag color="green">{{ record.target_field }}</a-tag>
              </template>
              <template v-if="column.key === 'field_type'">
                <a-tag color="blue">{{ record.field_type }}</a-tag>
              </template>
            </template>
          </a-table>

          <div class="mapping-actions">
            <a-space>
              <a-button type="primary" @click="handleProceedToSyncTask">
                <template #icon><RightOutlined /></template>
                继续创建同步任务
              </a-button>
              <a-button @click="handleClearMappings">
                清除映射
              </a-button>
            </a-space>
          </div>
        </div>

        <!-- 表统计信息 -->
        <div class="table-stats">
          <a-divider>表统计信息</a-divider>
          <a-row :gutter="16">
            <a-col :span="6">
              <a-statistic title="总字段数" :value="tableStructure.columns.length" />
            </a-col>
            <a-col :span="6">
              <a-statistic
                title="主键字段"
                :value="tableStructure.columns.filter(col => col.primary_key).length"
              />
            </a-col>
            <a-col :span="6">
              <a-statistic
                title="必填字段"
                :value="tableStructure.columns.filter(col => !col.nullable).length"
              />
            </a-col>
            <a-col :span="6">
              <a-statistic
                title="已映射字段"
                :value="mappedFields.length"
              />
            </a-col>
          </a-row>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else-if="!selectedTable" class="empty-state">
        <a-empty description="请选择要查看的表" />
      </div>
    </div>

    <!-- 创建同步任务模态框 -->
    <SyncTaskFormModal
      v-model:open="syncTaskModal.visible"
      :data-source="dataSource"
      :initial-data="syncTaskModal.initialData"
      @success="handleSyncTaskSuccess"
    />
  </a-modal>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import {
  ReloadOutlined,
  PlusOutlined,
  KeyOutlined,
  RightOutlined
} from '@ant-design/icons-vue'
import syncApi from '@/apis/sync_api'
import SyncTaskFormModal from './SyncTaskFormModal.vue'

const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  dataSource: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:open', 'refresh', 'create-sync-task'])

// 响应式数据
const loading = ref(false)
const selectedTable = ref('')
const availableTables = ref([])
const tableStructure = ref(null)

// 字段映射
const mappedFields = ref([])

// 同步任务模态框
const syncTaskModal = reactive({
  visible: false,
  initialData: null
})

// 计算属性
const modalVisible = computed(() => props.open)

// 处理模态框显示状态变化
const handleModalVisibleChange = (value) => {
  emit('update:open', value)
}

// 目标字段选项（态势对象表的字段）
const targetFields = [
  { label: '对象名称 (name)', value: 'name', type: 'string' },
  { label: '唯一编码 (code)', value: 'code', type: 'string' },
  { label: '对象类型 (object_type)', value: 'object_type', type: 'string' },
  { label: '型号 (model)', value: 'model', type: 'string' },
  { label: '所属单位 (organization)', value: 'organization', type: 'string' },
  { label: '部署状态 (deployment_status)', value: 'deployment_status', type: 'string' },
  { label: '探测距离 (detection_range)', value: 'detection_range', type: 'float' },
  { label: '响应时间 (response_time)', value: 'response_time', type: 'float' },
  { label: '精度 (accuracy)', value: 'accuracy', type: 'float' }
]

// 表格列配置
const columnColumns = [
  {
    title: '字段名',
    dataIndex: 'name',
    key: 'name',
    width: 180,
    fixed: 'left'
  },
  {
    title: '数据类型',
    dataIndex: 'type',
    key: 'type',
    width: 130
  },
  {
    title: '是否允许NULL',
    dataIndex: 'nullable',
    key: 'nullable',
    width: 110
  },
  {
    title: '主键',
    dataIndex: 'primary_key',
    key: 'primary_key',
    width: 70
  },
  {
    title: '默认值',
    dataIndex: 'default',
    key: 'default',
    width: 120
  },
  {
    title: '字段注释',
    dataIndex: 'comment',
    key: 'comment',
    width: 180
  },
  {
    title: '建议映射到',
    key: 'suggested_mapping',
    width: 200
  }
]

const mappingColumns = [
  {
    title: '源字段',
    dataIndex: 'source_field',
    key: 'source_field',
    width: 200
  },
  {
    title: '目标字段',
    dataIndex: 'target_field',
    key: 'target_field',
    width: 200
  },
  {
    title: '字段类型',
    dataIndex: 'field_type',
    key: 'field_type',
    width: 120
  },
  {
    title: '是否必需',
    dataIndex: 'is_required',
    key: 'is_required',
    width: 100,
    customRender: ({ text }) => text ? '是' : '否'
  },
  {
    title: '默认值',
    dataIndex: 'default_value',
    key: 'default_value',
    width: 150
  }
]

// 只监听模态框显示状态，打开时加载表列表
watch(() => props.open, (newValue) => {
  if (newValue && props.dataSource) {
    // 清空之前的数据
    selectedTable.value = ''
    tableStructure.value = null
    mappedFields.value = []
    // 加载表列表
    loadAvailableTables()
  } else if (!newValue) {
    // 关闭时清空数据
    selectedTable.value = ''
    tableStructure.value = null
    availableTables.value = []
    mappedFields.value = []
  }
})

// 方法
const filterTableOption = (input, option) => {
  return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

const loadAvailableTables = async () => {
  if (!props.dataSource) {
    return
  }

  try {
    loading.value = true

    // 测试连接以获取可用表列表
    const response = await syncApi.testConnection(props.dataSource.id)

    if (response.success) {
      availableTables.value = response.available_tables || []
      message.success(`成功获取 ${availableTables.value.length} 个表`)
    } else {
      message.error('获取表列表失败：' + response.message)
      availableTables.value = []
    }
  } catch (error) {
    console.error('获取表列表失败:', error)
    message.error('获取表列表失败：' + (error.message || '未知错误'))
    availableTables.value = []
  } finally {
    loading.value = false
  }
}

const handleTableChange = async (tableName) => {
  if (!tableName || !props.dataSource) return

  try {
    loading.value = true
    tableStructure.value = await syncApi.getTableStructure(props.dataSource.id, tableName)

    // 清空之前的映射
    mappedFields.value = []

    // 为每个字段添加建议映射
    tableStructure.value.columns.forEach(column => {
      column.suggested_mapping = suggestMapping(column.name)
    })
  } catch (error) {
    message.error('获取表结构失败：' + (error.message || '未知错误'))
    tableStructure.value = null
  } finally {
    loading.value = false
  }
}

const suggestMapping = (fieldName) => {
  const lowerFieldName = fieldName.toLowerCase()

  // 简单的字段名匹配逻辑
  const mappingRules = [
    { patterns: ['name', 'title', '名称', '标题'], target: 'name' },
    { patterns: ['code', 'id', '编号', '编码'], target: 'code' },
    { patterns: ['type', '类别', '类型'], target: 'object_type' },
    { patterns: ['model', '型号', 'model_name'], target: 'model' },
    { patterns: ['org', 'organization', '单位', '组织'], target: 'organization' },
    { patterns: ['status', 'state', '状态'], target: 'deployment_status' },
    { patterns: ['range', '距离', '探测范围'], target: 'detection_range' },
    { patterns: ['time', '响应', 'response'], target: 'response_time' },
    { patterns: ['accuracy', '精度', '准确度'], target: 'accuracy' }
  ]

  for (const rule of mappingRules) {
    for (const pattern of rule.patterns) {
      if (lowerFieldName.includes(pattern)) {
        return rule.target
      }
    }
  }

  return null
}

const handleMappingChange = (column, targetField) => {
  if (!targetField) {
    // 移除映射
    mappedFields.value = mappedFields.value.filter(
      field => field.source_field !== column.name
    )
    return
  }

  // 查找目标字段配置
  const targetFieldConfig = targetFields.find(field => field.value === targetField)
  if (!targetFieldConfig) return

  // 创建或更新映射
  const existingIndex = mappedFields.value.findIndex(
    field => field.source_field === column.name
  )

  const mappingData = {
    source_field: column.name,
    target_field: targetField,
    field_type: targetFieldConfig.type,
    is_required: !column.nullable || targetField === 'name' || targetField === 'code' || targetField === 'object_type',
    default_value: column.default || ''
  }

  if (existingIndex >= 0) {
    mappedFields.value[existingIndex] = mappingData
  } else {
    mappedFields.value.push(mappingData)
  }
}

const handleClearMappings = () => {
  mappedFields.value = []
  tableStructure.value?.columns.forEach(column => {
    column.suggested_mapping = null
  })
}

const handleCreateSyncTask = () => {
  if (!selectedTable.value) {
    message.warning('请先选择表')
    return
  }

  syncTaskModal.initialData = {
    source_table: selectedTable.value,
    field_mappings: [...mappedFields.value]
  }
  syncTaskModal.visible = true
}

const handleProceedToSyncTask = () => {
  handleCreateSyncTask()
}

const handleSyncTaskSuccess = () => {
  syncTaskModal.visible = false
  syncTaskModal.initialData = null
  emit('create-sync-task')
  emit('update:open', false)
}
</script>

<style scoped>
.table-structure-container {
  max-height: 80vh;
  overflow-y: auto;
}

.datasource-info {
  margin-bottom: 16px;
}

.table-selection {
  margin-bottom: 16px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.table-structure {
  margin-top: 16px;
}

.structure-table {
  margin-bottom: 16px;
}

.mapping-preview {
  margin-top: 24px;
  padding: 16px;
  background: #f0f7ff;
  border-radius: 6px;
}

.mapping-table {
  margin-bottom: 16px;
}

.mapping-actions {
  text-align: center;
  margin-top: 16px;
}

.table-stats {
  margin-top: 24px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

:deep(.ant-table-thead > tr > th) {
  background: #f5f5f5;
  font-weight: 600;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: #f0f7ff;
}

:deep(.ant-statistic-title) {
  font-size: 14px;
  color: #666;
}

:deep(.ant-statistic-content) {
  font-size: 20px;
  font-weight: 500;
}

:deep(.ant-divider-horizontal.ant-divider-with-text) {
  margin: 20px 0;
}

:deep(.ant-descriptions-item-label) {
  font-weight: 500;
}
</style>